#ifndef CODEOBFUSCATION_H
#define CODEOBFUSCATION_H

#include <QObject>
#include <QTimer>
#include <QCryptographicHash>
#include <QRandomGenerator>
#include <functional>
#include <vector>

// 代码混淆和运行时完整性检查系统
class CodeObfuscation : public QObject
{
    Q_OBJECT

public:
    static CodeObfuscation& instance();

    // 初始化混淆系统
    void initializeObfuscation();

    // 运行时完整性检查
    bool verifyCodeIntegrity();
    bool verifyMemoryIntegrity();
    bool verifyControlFlow();

    // 混淆执行函数
    template<typename T>
    T obfuscatedExecution(std::function<T()> func);

    // 关键函数包装
    bool executeSecureFunction(const QString& functionId, std::function<bool()> func);

    // 反调试陷阱
    void setupDebugTraps();
    bool isBeingDebugged();

    // 控制流混淆
    void obfuscateControlFlow();
    int calculateObfuscatedValue(int input);

private:
    explicit CodeObfuscation(QObject *parent = nullptr);
    ~CodeObfuscation();

    static CodeObfuscation* s_instance;

    // 完整性检查状态
    struct IntegrityState {
        bool isInitialized = false;
        QByteArray baselineHash;
        std::vector<QByteArray> criticalSections;
        int violationCount = 0;
        qint64 lastCheckTime = 0;
    };
    IntegrityState m_integrityState;

    // 混淆状态
    struct ObfuscationState {
        uint32_t xorKey = 0;
        int rotationCount = 0;
        bool isActive = false;
        std::vector<int> dummyValues;
    };
    ObfuscationState m_obfuscationState;

    QTimer* m_integrityTimer;
    QTimer* m_obfuscationTimer;

    // 内部检查函数
    QByteArray calculateMemoryChecksum();
    bool checkStackIntegrity();
    bool checkHeapIntegrity();
    void injectNoisyInstructions();

    // 反调试技术
    bool detectSoftwareBreakpoints();
    bool detectHardwareBreakpoints();
    bool detectStepByStep();
    bool detectMemoryPatching();

    // 控制流保护
    void validateCallStack();
    bool verifyReturnAddress();

    // 陷阱函数
    void triggerIntegrityTrap();
    void activateCountermeasures();

private slots:
    void performIntegrityCheck();
    void rotateObfuscation();

signals:
    void integrityViolationDetected();
    void debuggingAttemptDetected();
    void memoryTamperingDetected();
};

// 高级混淆宏系统
#define OBFUSCATED_CALL(func) \
    CodeObfuscation::instance().executeSecureFunction(#func, [&]() -> bool { \
        return func(); \
    })

#define INTEGRITY_GUARD(code) \
    do { \
        if (!CodeObfuscation::instance().verifyCodeIntegrity()) { \
            return false; \
        } \
        code; \
    } while(0)

// 混淆的数值计算
#define OBFUSCATED_INT(val) \
    CodeObfuscation::instance().calculateObfuscatedValue(val)

// 反调试执行
#define ANTI_DEBUG_EXECUTE(normalCode, debugDetectedCode) \
    do { \
        if (CodeObfuscation::instance().isBeingDebugged()) { \
            debugDetectedCode; \
        } else { \
            normalCode; \
        } \
    } while(0)

// 控制流混淆
#define OBFUSCATED_BRANCH(condition, trueCode, falseCode) \
    do { \
        volatile bool _cond = condition; \
        for(int _i = 0; _i < QRandomGenerator::global()->bounded(2, 5); ++_i) { \
            _cond = _cond ^ (QRandomGenerator::global()->bounded(2) == 0); \
        } \
        _cond = _cond ^ (QRandomGenerator::global()->bounded(2) == 0); \
        if(_cond) { trueCode; } else { falseCode; } \
    } while(0)

// 时间炸弹宏
#define TIME_BOMB_CHECK(maxDays) \
    do { \
        static qint64 _startTime = QDateTime::currentMSecsSinceEpoch(); \
        qint64 _currentTime = QDateTime::currentMSecsSinceEpoch(); \
        if ((_currentTime - _startTime) > (maxDays * 24 * 60 * 60 * 1000)) { \
            return false; \
        } \
    } while(0)

#endif // CODEOBFUSCATION_H